package com.example.auth.Configuration.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 配置 Feign 微服务间 RPC 调用携带的 token
 *
 * @author Ringo
 * @date 2021/10/19 20:54
 */
@Component
public class OAuth2RequestInterceptor implements RequestInterceptor {

    public static final String CLIENT_ID = "client_id";

    public static final String CLIENT_SECRET = "123";

    public static final String GRANT_TYPE = "client_credentials";

    public static final String SCOPE = "APPLICATION";

    public static final String URL = "http://localhost:8082/oauth/token";

    @Autowired
    private RestTemplate restTemplate;

    private Logger logger = LoggerFactory.getLogger(OAuth2RequestInterceptor.class);

    @Override
    public void apply(RequestTemplate template) {
        String accessToken = "";
        try {
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("client_id", CLIENT_ID);
            map.add("client_secret", CLIENT_SECRET);
            map.add("grant_type", GRANT_TYPE);
            map.add("SCOPE", SCOPE);
            Map<String, String> resp = restTemplate.postForObject(URL, map, Map.class);

            assert resp != null;
            // 获得 access_token
            accessToken = resp.get("access_token");

            // 获得过期时间, 加入到 Redis 缓存, 防止重复获取令牌
            // resp.get("expires_in");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }

        // access_token 加入到请求头
        template.header("Authorization", "Bearer " + accessToken);
    }

}
